import Vue from "vue";
import OriginSidelip from "./index.vue";
const SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g;
const MOZ_HACK_REGEXP = /^moz([A-Z])/;
function camelCase(name) {
  return name
      .replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) {
          return offset ? letter.toUpperCase() : letter;
      })
      .replace(MOZ_HACK_REGEXP, "Moz$1");
}
function getStyle(element, styleName) {
  if (!element || !styleName) return null;
  styleName = camelCase(styleName);
  if (styleName === "float") {
      styleName = "cssFloat";
  }
  try {
      const computed = document.defaultView.getComputedStyle(element, "");
      return element.style[styleName] || computed ? computed[styleName] : null;
  } catch (e) {
      return element.style[styleName];
  }
}
class Sidelip {
  constructor(iframeSrc = '', option = {}, callback, hostCom) {
    let self = this;
    this.callback = callback;
    this.instance = new Vue({
      el: document.createElement("div"),
      render(createElement) {
        return createElement(
          OriginSidelip,
          {
            props: {
              iframeSrc,
              fromApp: option.fromApp,
              iframeLoginUrl: option.iframeLoginUrl
            },
            on: {
              Close: data => {
                self.close(data);
              }
            }
          }
        );
      }
    });

    let container = document.querySelector(".single-page") || hostCom.$el.parentElement;
    const containerPosition = getStyle(container, "positon");
    if (containerPosition === "static" || !containerPosition) {
      container.style.position = "relative";
      containerPosition &&
        $channel.$once("ResetContainerStyle", () => {
          container.style.position = containerPosition;
        });
    }
    const scrollTop = container.scrollTop;
    this.containerInfo = {
      container,
      scrollTop
    };
    container.scrollTop = 0;
    container.style.overflowY = "hidden";
    container.appendChild(this.instance.$el);
    $channel.$once("RouterChangeBefore", () => {
      this.close();
    });
  }
  close(data) {
    // if (this.instance.$children.length < 1) {
    //   return;
    // }
    const { container, scrollTop } = this.containerInfo;
    container.scrollTop = scrollTop;
    container.style.overflowY = "auto";

    setTimeout(() => {
      const child = this.instance && this.instance.$children[0];
      child && child.$destroy && child.$destroy();
      if (this.callback) {
        this.callback(data);
        this.callback = null;
      }

      $channel.$emit("ResetContainerStyle");
      // $once 触发之后，监听器就会被移除。
      // $channel.$off("RouterChangeBefore");
      this.instance = null;
      // $instanceSidelipArray.pop();
    }, 100);
  }
}
export default Sidelip;

